/**
 * Global Teardown for TaskMaster E2E Tests
 * AceFlow v3.0 - E2E Testing Phase
 */

/**
 * Global teardown function
 * Runs after all tests to clean up the test environment
 */
async function globalTeardown() {
  console.log('🧹 Starting TaskMaster E2E Test Cleanup...');

  try {
    // Clean up test database files
    const fs = await import('fs');
    const path = await import('path');

    const testDbDir = path.join(process.cwd(), '../backend/test_db');
    if (fs.existsSync(testDbDir)) {
      const files = fs.readdirSync(testDbDir);
      for (const file of files) {
        if (file.endsWith('.db')) {
          const filePath = path.join(testDbDir, file);
          fs.unlinkSync(filePath);
          console.log(`🗑️  Deleted test database: ${file}`);
        }
      }
    }

    // Clean up screenshots directory
    const screenshotsDir = path.join(process.cwd(), 'screenshots');
    if (fs.existsSync(screenshotsDir)) {
      const files = fs.readdirSync(screenshotsDir);
      for (const file of files) {
        const filePath = path.join(screenshotsDir, file);
        fs.unlinkSync(filePath);
      }
      console.log(`🗑️  Cleaned up ${files.length} screenshot files`);
    }

    // Clean up test results
    const resultsDir = path.join(process.cwd(), 'test-results');
    if (fs.existsSync(resultsDir)) {
      fs.rmSync(resultsDir, { recursive: true, force: true });
      console.log('🗑️  Cleaned up test results directory');
    }

    console.log('✅ Test environment cleanup complete!');

  } catch (error) {
    console.error('❌ Error during cleanup:', error.message);
  }
}

export default globalTeardown;
